package com;

import java.util.concurrent.*;

/**
 * 线程池例子 + 自定义多线程
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
//        ExecutorService executorService = Executors.newFixedThreadPool(5);
//        for (int i = 0; i < 10; i++) {
//            executorService.execute(new Run());
//        }
        ExecutorService executorService1 = new ThreadPoolExecutor(
                2,
                5,
                3L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardPolicy());
        try {
            for (int i = 0; i < 15; i++) {
                int temp = i;
                executorService1.execute(()->{
                    System.out.println(Thread.currentThread().getName() + "在执行任务" + String.valueOf(temp));
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }finally {
            executorService1.shutdown();
        }

    }
}
class Run implements Runnable{

    public void run() {
        System.out.println(Thread.currentThread().getName() + "正在执行任务");
    }
}

